#include "widget.h"
#include "ui_widget.h"
#include <QMetaType>

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);

    server = new QTcpServer;
    server->listen(QHostAddress::AnyIPv4,PORT);
    qDebug() << "服务器等待新的客户端连接";
    connect(server,&QTcpServer::newConnection,this,&Widget::newClientHandler);
}

Widget::~Widget()
{
    delete ui;
}


void Widget::newClientHandler()
{
    qDebug() << "服务器接收到一个新的客户端连接";
    QTcpSocket *client = server->nextPendingConnection();

    struct MySocketInfo _MySocketInfo;
    _MySocketInfo.client = client;
    _MySocketInfo.ipaddr = client->peerAddress().toString();
    _MySocketInfo.port = client->peerPort();
    v.push_back(_MySocketInfo);

    ui->iplineEdit->setText(client->peerAddress().toString());
    ui->portlineEdit->setText(QString::number(client->peerPort()));

    // 启动线程
    myThread *t = new myThread(client);
    t->start();
    connect(t,&myThread::threadinfosendtoWidget,this,&Widget::threadinfo);

}

void Widget::threadinfo(QByteArray b,QTcpSocket *client)
{
    ui->mainlineEdit->setText(QString(b));
    ui->iplineEdit->setText(client->peerAddress().toString());
    ui->portlineEdit->setText(QString::number(client->peerPort()));
}
